
package db.manager;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import app.BaseApplication;

import com.netease.util.PDEEngine;

import db.XoneDBTables.AccountTable;

public class ManagerAccount {

    private static Context mContext = BaseApplication.getAppInstance().getApplicationContext();
    public static String NAME_ANONUMOUS = "anonymous";
    public static String PASSWORD_ANONUMOUS = "anonymous";
    private Account mCurAccount;
    private static ManagerAccount sInstance = null;

    public static String[] WEIBOACCOUNT_PRO = new String[] {
            AccountTable.C_USER_ACCOUNT, // 1
            AccountTable.C_USER_PASSWORD, // 2
            AccountTable.C_USER_ID, // 3
            AccountTable.C_USER_NICKNAME, // 4
            AccountTable.C_USER_AVATAR, // 5
            AccountTable.C_USER_TYPE, // 6
            AccountTable.C_LAST_LOGIN, // 7
            AccountTable.C_USER_ATTR,//9
    };

    public static final int COLUMNS_ID = 0;
    public static final int COLUMNS_ACCOUNT = 1;
    public static final int COLUMNS_PASSWORD = 2;
    public static final int COLUMNS_USER_ID = 3;
    public static final int COLUMNS_NICKNAME = 4;
    public static final int COLUMNS_AVATAR = 5;
    public static final int COLUMNS_TYPE = 6;
    public static final int COLUMNS_LOGIN = 7;
    public static final int COLUMNS_USER_ATTR = 9;

    public static class Account {
        public String mUserName;
        public String mPassword;
        public String mNickName;
        public String mUserId;
        public String mAvatar;
        public int mUserType;
        public boolean mIsLastLogin;
        public int mAttr;//协议返回，这里用于判断是否要加v或者官方用户
    }

    public static synchronized ManagerAccount getInstance() {
        if (sInstance == null) {
            sInstance = new ManagerAccount();
        }
        return sInstance;
    }

    /**
     * 获取最后一次登录帐号
     *
     * @return Account
     */
    public Account getLastLoginAccount() {
        Account acc = null;
        String selection = AccountTable.C_LAST_LOGIN + " = 1";
        Cursor c = mContext.getContentResolver().query(AccountTable.CONTENT_URI, null, selection,
                null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    acc = new Account();
                    acc.mUserName = c.getString(COLUMNS_ACCOUNT);
                    acc.mPassword = c.getString(COLUMNS_PASSWORD);
                    acc.mNickName = c.getString(COLUMNS_NICKNAME);
                    acc.mUserId = c.getString(COLUMNS_USER_ID);
                    acc.mUserType = c.getInt(COLUMNS_TYPE);
                    acc.mAvatar = c.getString(COLUMNS_AVATAR);
                    acc.mIsLastLogin = c.getInt(COLUMNS_LOGIN) == 1 ? true : false;
                    acc.mAttr = c.getInt(COLUMNS_USER_ATTR);
                    String pwEnc = PDEEngine.PDecrypt(mContext, acc.mPassword);
                    if (!TextUtils.isEmpty(pwEnc)) {
                        acc.mPassword = pwEnc;
                    }
                }
            } finally {
                c.close();
            }
        }
        return acc;
    }

    /**
     * 设置当前登录帐号
     *
     * @param Account
     * @return
     */
    public boolean setLoginAccount(Account acc) {
        boolean ret = false;
        if (null == acc) {
            return ret;
        }
        Account oldacc = null;
        if (acc.mUserName != null) {
            oldacc = getAccount(acc.mUserName);
        }
        logout();
        if (null != oldacc) {
            ret = updateAccountByUserName(acc);
        } else {
            ret = addAccount(acc);
        }
        return ret;
    }

    /**
     * 清除当前登录状态
     */
    public int logout() {
        mCurAccount = null;
        ContentValues values = new ContentValues();
        values.put(AccountTable.C_LAST_LOGIN, "0");
        String selection = AccountTable.C_LAST_LOGIN + "=?";
        String[] selectionArgs = new String[] {
            String.valueOf(1)
        };
        return mContext.getContentResolver().update(AccountTable.CONTENT_URI, values, selection,
                selectionArgs);
    }

    /**
     * 获取帐号
     *
     * @param user_name
     * @return
     */
    public Account getAccount(String user_name) {
        Account acc = null;
        if (!TextUtils.isEmpty(user_name)) {
            String selection = AccountTable.C_USER_ACCOUNT + "=?";
            String[] selectionArgs = new String[] {
                user_name
            };
            Cursor c = mContext.getContentResolver().query(AccountTable.CONTENT_URI, null,
                    selection, selectionArgs, null);
            if (c != null) {
                try {
                    if (c.moveToFirst()) {
                        acc = new Account();
                        acc.mUserName = c.getString(COLUMNS_ACCOUNT);
                        acc.mPassword = c.getString(COLUMNS_PASSWORD);
                        acc.mNickName = c.getString(COLUMNS_NICKNAME);
                        acc.mUserId = c.getString(COLUMNS_USER_ID);
                        acc.mUserType = c.getInt(COLUMNS_TYPE);
                        acc.mAvatar = c.getString(COLUMNS_AVATAR);
                        acc.mIsLastLogin = c.getInt(COLUMNS_LOGIN) == 1 ? true : false;
                        acc.mAttr = c.getInt(COLUMNS_USER_ATTR);
                        String pwEnc = PDEEngine.PDecrypt(mContext, acc.mPassword);
                        if (!TextUtils.isEmpty(pwEnc)) {
                            acc.mPassword = pwEnc;
                        }
                    }
                } finally {
                    c.close();
                }
            }
        }
        return acc;
    }

    /**
     * 获取当前最新帐号
     *
     * @param
     * @return
     */
    public Account getNewestAccount() {
        Account acc = null;
        String selection = AccountTable.C_USER_ACCOUNT + " <>?";
        String[] selectionArgs = new String[] {
            NAME_ANONUMOUS
        };
        Cursor c = mContext.getContentResolver().query(AccountTable.CONTENT_URI, null, selection,
                selectionArgs, "_id" + " DESC");
            if (c != null) {
                try {
                    if (c.moveToFirst()) {
                        acc = new Account();
                        acc.mUserName = c.getString(COLUMNS_ACCOUNT);
                        acc.mPassword = c.getString(COLUMNS_PASSWORD);
                        acc.mNickName = c.getString(COLUMNS_NICKNAME);
                        acc.mUserId = c.getString(COLUMNS_USER_ID);
                        acc.mUserType = c.getInt(COLUMNS_TYPE);
                        acc.mAvatar = c.getString(COLUMNS_AVATAR);
                        acc.mIsLastLogin = c.getInt(COLUMNS_LOGIN) == 1 ? true : false;
                        acc.mAttr = c.getInt(COLUMNS_USER_ATTR);
                        String pwEnc = PDEEngine.PDecrypt(mContext, acc.mPassword);
                        if (!TextUtils.isEmpty(pwEnc)) {
                            acc.mPassword = pwEnc;
                        }
                    }
                } finally {
                    c.close();
                }
            }
        return acc;
    }

    /**
     * 更新用户帐号表中某一user_account所对应的数据项
     *
     * @param Account
     * @return
     */
    public boolean updateAccountByUserName(Account user) {
        ContentValues values = new ContentValues();
        values.clear();
        if (null != user.mPassword) {
            String pwEnc = PDEEngine.PEncrypt(mContext, user.mPassword);
            if (!TextUtils.isEmpty(pwEnc)) {
                user.mPassword = pwEnc;
            }
            values.put(AccountTable.C_USER_PASSWORD, user.mPassword);
        }
        if (null != user.mNickName) {
            values.put(AccountTable.C_USER_NICKNAME, user.mNickName);
        }
        if (null != user.mUserId) {
            values.put(AccountTable.C_USER_ID, user.mUserId);
        }
        if (null != user.mAvatar) {
            values.put(AccountTable.C_USER_AVATAR, user.mAvatar);
        }
        values.put(AccountTable.C_USER_TYPE, user.mUserType);
        values.put(AccountTable.C_LAST_LOGIN, user.mIsLastLogin ? 1 : 0);
        values.put(AccountTable.C_USER_ATTR, user.mAttr);
//        values.put(AccountTable.C_UPDATE_TIME, System.currentTimeMillis());

        String selection = AccountTable.C_USER_ACCOUNT + "=?";
        String[] selectionArgs = new String[] {
            user.mUserName
        };
        int ret = mContext.getContentResolver().update(AccountTable.CONTENT_URI, values, selection,
                selectionArgs);
        if (ret > 0)
            return true;
        else
            return false;
    }

    /**
     * 向用户帐号表中插入一项
     *
     * @param Account
     * @return
     */
    public boolean addAccount(Account user) {
        if (null == user) {
            return false;
        }
        ContentValues values = new ContentValues();
        if (null != user.mUserName) {
            values.put(AccountTable.C_USER_ACCOUNT, user.mUserName);
        }
        if (null != user.mPassword) {
            String pwEnc = PDEEngine.PEncrypt(mContext, user.mPassword);
            if (!TextUtils.isEmpty(pwEnc)) {
                user.mPassword = pwEnc;
            }
            values.put(AccountTable.C_USER_PASSWORD, user.mPassword);
        }
        if (null != user.mNickName) {
            values.put(AccountTable.C_USER_NICKNAME, user.mNickName);
        }
        if (null != user.mUserId) {
            values.put(AccountTable.C_USER_ID, user.mUserId);
        }
        if (null != user.mAvatar) {
            values.put(AccountTable.C_USER_AVATAR, user.mAvatar);
        }
        values.put(AccountTable.C_USER_TYPE, user.mUserType);
        values.put(AccountTable.C_LAST_LOGIN, user.mIsLastLogin ? 1 : 0);
        values.put(AccountTable.C_UPDATE_TIME, System.currentTimeMillis());
        values.put(AccountTable.C_USER_ATTR, user.mAttr);
        Uri uri = mContext.getContentResolver().insert(AccountTable.CONTENT_URI, values);
        try {
            if (uri == null || ContentUris.parseId(uri) < 0) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取登录过的所有账号
     *
     * @return
     */
    public List<Account> getAllAccountsList() {
        List<Account> list = new ArrayList<Account>();
        String selection = AccountTable.C_USER_ACCOUNT + " <>?";
        String[] selectionArgs = new String[] {
            NAME_ANONUMOUS
        };

        Cursor c = mContext.getContentResolver().query(AccountTable.CONTENT_URI, null, selection,
                selectionArgs, "_id" + " DESC");
        if (c != null) {
            for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
                Account acc = new Account();
                acc.mUserName = c.getString(COLUMNS_ACCOUNT);
                acc.mPassword = c.getString(COLUMNS_PASSWORD);
                acc.mNickName = c.getString(COLUMNS_NICKNAME);
                acc.mUserId = c.getString(COLUMNS_USER_ID);
                acc.mUserType = c.getInt(COLUMNS_TYPE);
                acc.mAvatar = c.getString(COLUMNS_AVATAR);
                acc.mIsLastLogin = c.getInt(COLUMNS_LOGIN) == 1 ? true : false;
                acc.mAttr = c.getInt(COLUMNS_USER_ATTR);
                String pwEnc = PDEEngine.PDecrypt(mContext, acc.mPassword);
                if (!TextUtils.isEmpty(pwEnc)) {
                    acc.mPassword = pwEnc;
                }
                list.add(acc);
            }
            c.close();
        }

        return list;
    }

    /**
     * 按显示需求获取登录过的所有帐号
     *
     * @return
     */
    public Cursor getAllAccounts() {
        String selection = AccountTable.C_USER_ACCOUNT + " <>?";
        String[] selectionArgs = new String[] {
            NAME_ANONUMOUS
        };
        Cursor c = mContext.getContentResolver().query(AccountTable.CONTENT_URI, null, selection,
                selectionArgs, AccountTable.C_LAST_LOGIN + " DESC");

        return c;
    }

    /**
     * 删除指定用户名的帐号
     *
     * @param String
     * @return
     */
    public void deleteAccountByName(String user_name) {

        if (TextUtils.isEmpty(user_name))
            return;
        String where = AccountTable.C_USER_ACCOUNT + " =?";
        String[] selectionArgs = new String[] {
            user_name
        };
        mContext.getContentResolver().delete(AccountTable.CONTENT_URI, where, selectionArgs);
        if(mCurAccount != null && mCurAccount.mUserName.equals(user_name)) {
            mCurAccount = null;
        }
    }

    /**
     * 删除指定userid的帐号
     *
     * @param String
     * @return
     */
    public void deleteAccountByUserId(String user_id) {

        if (TextUtils.isEmpty(user_id))
            return;
        String where = AccountTable.C_USER_ID + " =?";
        String[] selectionArgs = new String[] {
                user_id
        };
        mContext.getContentResolver().delete(AccountTable.CONTENT_URI, where, selectionArgs);
        if(mCurAccount != null && mCurAccount.mUserId.equals(user_id)) {
            mCurAccount = null;
        }
    }

    /**
     * 删除所有账号
     *
     * @return
     */
    public void deleteAllAccount() {
        mContext.getContentResolver().delete(AccountTable.CONTENT_URI, null, null);
        mCurAccount = null;
    }

    /**
     * 获取当前登录帐号的用户名，若不存在，则返回匿名
     *
     * @return
     */
    public String getCurrentAccountName() {
        String name = null;
        if (mCurAccount != null) {
            name = mCurAccount.mUserName;
        } else {
            Account acc = getLastLoginAccount();
            if (acc != null) {
                name = acc.mUserName;
                mCurAccount = acc;
            } else {
                name = NAME_ANONUMOUS;
            }
        }
        return name;
    }

    /**
     * 获取当前登录帐号的用户id
     *
     * @return
     */
    public String getCurrentAccountId() {
        String userId = null;
        if (mCurAccount != null) {
            userId = mCurAccount.mUserId;
        } else {
            Account acc = getLastLoginAccount();
            if (acc != null) {
                userId = acc.mUserId;
                mCurAccount = acc;
            }
        }
        return userId;
    }

    /**
     * 获取当前登录帐号的用户
     *
     * @return
     */
    public Account getCurrentAccount() {
        Account acc;
        if (mCurAccount != null) {
            acc = mCurAccount;
        } else {
            acc = getLastLoginAccount();
        }
        return acc;
    }

    /**
     * 判断当前是否有正常用户登录（非匿名）
     *
     * @return
     */
    public boolean isNormalLoginUser() {
        boolean res = true;
        if (getCurrentAccountName().equals(NAME_ANONUMOUS)) {
            res = false;
        }
        return res;
    }

    /**
     * 根据userId更新昵称和头像
     *
     * @return
     */
    public boolean updateNickAndAvatarByUserId(String userId,String nickName,String avatar){
        if(TextUtils.isEmpty(userId)){
            return false;
        }
        ContentValues values = new ContentValues();
        values.clear();

        if (!TextUtils.isEmpty(nickName)) {
            values.put(AccountTable.C_USER_NICKNAME, nickName);
        }
        if (!TextUtils.isEmpty(avatar)) {
            values.put(AccountTable.C_USER_AVATAR,avatar);
        }

        String selection = AccountTable.C_USER_ID + "=?";
        String[] selectionArgs = new String[] {
                userId
        };
        int ret = mContext.getContentResolver().update(AccountTable.CONTENT_URI, values, selection,
                selectionArgs);
        if (ret > 0) {
            if(mCurAccount != null && mCurAccount.mUserId.equals(userId)) {
                mCurAccount = null;
            }
            return true;
        }
        else
            return false;
    }

    /**
     * 给push的跨进程使用
     *
     * @return
     */
    public static String getCurAccountId() {
        String userId = null;
        String selection = AccountTable.C_LAST_LOGIN + " = 1";
        Cursor c = mContext.getContentResolver().query(AccountTable.CONTENT_URI, null, selection,
                null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    userId = c.getString(COLUMNS_USER_ID);
                }
            } finally {
                c.close();
            }
        }
        return userId;
    }
}
